<script setup lang="ts">
import { postPatientAddAPI, putPatientUpdateAPI } from '@/api/user'
import type { PostPatientAddParams, PutPatientUpdateParams } from '@/types/user'
import { computed, ref, watch, onMounted } from 'vue'

const query = defineProps<{
  id?: string
  patientInfo?: string
}>()

// 判断是否为编辑模式
const isEdit = computed(() => Boolean(query.id))

if (isEdit.value) {
  // 更改标题
  uni.setNavigationBarTitle({
    title: '编辑患者信息',
  })
}

// 表单数据
const form = ref<PostPatientAddParams & { id?: string }>({
  name: '',
  idCard: '',
  gender: undefined,
  defaultFlag: 1,
})

// 在页面加载时回显数据
onMounted(() => {
  if (isEdit.value && query.patientInfo) {
    try {
      const patient = JSON.parse(decodeURIComponent(query.patientInfo))
      // 回显表单数据
      form.value = {
        id: patient.id,
        name: patient.name,
        idCard: patient.idCard,
        gender: patient.gender,
        defaultFlag: patient.defaultFlag,
      }
    } catch (error) {
      console.error('解析患者数据失败:', error)
    }
  }
})

// 根据身份证号计算性别
const computedGender = computed(() => {
  if (form.value.idCard.length === 18) {
    const idCard: string = form.value.idCard.slice(16, 17)
    return Number(idCard) % 2 === 0 ? 0 : 1 // 偶数为女(0)，奇数为男(1)
  }
  return undefined
})

// 监听身份证号变化，自动设置性别
watch(computedGender, (newGender) => {
  form.value.gender = newGender
})

// 切换默认就诊人
const handleChangeDefaultFlag = (e: UniHelper.SwitchOnChangeEvent) => {
  form.value.defaultFlag = e.detail.value ? 1 : 0
}

// 规则
const rules = ref<UniHelper.UniFormsRules>({
  name: {
    rules: [
      { required: true, errorMessage: '请填写患者姓名' },
      { pattern: /^(?:[\u4e00-\u9fa5·]{2,16})$/, errorMessage: '请填写真实姓名' },
    ],
  },
  idCard: {
    rules: [
      { required: true, errorMessage: '请填写患者身份证号' },
      {
        pattern:
          /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/,
        errorMessage: '请填写正确的身份证号',
      },
    ],
  },
  gender: {
    rules: [
      {
        validateFunction: function (rule, value, data, callback) {
          if (+form.value.idCard.charAt(16) % 2 !== value) {
            callback('选择的性别与身份号中性别不一致')
          }
          return true
        },
      },
    ],
  },
})

// 表单实例
const formRef = ref<UniHelper.UniFormsInstance>()
// 表单验证
const handleSubmit = async () => {
  try {
    await formRef.value?.validate!()
    // 判断是编辑还是添加
    if (isEdit.value) {
      // 编辑
      const res = await putPatientUpdateAPI(form.value as PutPatientUpdateParams)
    } else {
      // 添加
      const res = await postPatientAddAPI(form.value)
    }
    // #ifdef H5
    window.history.back()
    // #endif

    // #ifdef MP-WEIXIN
    await uni.navigateBack()
    // #endif

    uni.showToast({
      title: isEdit.value ? '编辑成功' : '添加成功',
      icon: 'success',
    })
  } catch (error) {
    console.log('error', error)
  }
}
</script>

<template>
  <scroll-view>
    <view class="archive-page">
      <uni-forms border label-width="220rpx" ref="formRef" :model="form" :rules="rules">
        <uni-forms-item label="患者姓名" name="name">
          <uni-easyinput
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :styles="{
              color: '#121826',
              backgroundColor: '#fff',
              disableColor: '#eee',
              borderColor: 'transparent',
            }"
            :input-border="false"
            :clearable="false"
            placeholder="请填写真实姓名"
            v-model="form.name"
          />
        </uni-forms-item>
        <uni-forms-item label="患者身份证号" name="idCard">
          <uni-easyinput
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :styles="{
              color: '#121826',
              backgroundColor: '#fff',
              disableColor: '#eee',
              borderColor: 'transparent',
            }"
            :input-border="false"
            :clearable="false"
            placeholder="请填写身份证号"
            v-model="form.idCard"
            :maxlength="18"
          />
        </uni-forms-item>
        <uni-forms-item label="患者性别" name="gender">
          <uni-data-checkbox
            selectedColor="#16C2A3"
            :localdata="[
              { text: '男', value: 1 },
              { text: '女', value: 0 },
            ]"
            v-model="form.gender"
          />
        </uni-forms-item>
        <uni-forms-item label="默认就诊人" name="defaultFlag">
          <view class="uni-switch">
            <switch
              :checked="Boolean(form.defaultFlag)"
              color="#20c6b2"
              style="transform: scale(0.7)"
              @change="handleChangeDefaultFlag"
            />
          </view>
        </uni-forms-item>
        <button class="uni-button" @click="handleSubmit">保存</button>
      </uni-forms>
      {{ form }}
    </view>
  </scroll-view>
</template>

<style lang="scss">
@import './index.scss';
</style>
